<?php
namespace app\index\controller;

//use WeChat\wechatClass;
use HongBao\wetRedClass;
use think\Controller;
use think\Db;
use think\Session;
class Index extends Controller{

	//大转盘页面
    public function index()
    {
        $id = input('id');
        if(empty($id))$this->error('参数为空!');
        $user_info = Session::get('user_info');
        
        if(empty($user_info)){
            $wechat = new wetRedClass();
            $openid = input('openid');
           
            if(empty($openid)){
                $wechat->index($id);
            }else{
                $member_result = db('member')->where(['wx_openid'=>$openid])->find();

                if(empty($member_result)){
                    $data['create_time'] = time();
                    $data['wx_openid'] = $openid;
                    db('member')->insert($data);
                    $member_result = db('member')->where(['wx_openid'=>$openid])->find();
                }

                Session::set('user_info',$member_result);
                $user_info = Session::get('user_info');
            }
        }

        $activity = db('activity')->where(['id'=>$id])->find();

        //查询奖品
        $activity_prizes_list = db('activity_prizes')->where(['aid'=>$id])->select();
        
        if(!empty($activity_prizes_list)){
            foreach ($activity_prizes_list as $key => $value) {
                $activity_prizes_name[]=$value['prize_name'];//只取出奖品名  
            }
        }else{
            $activity_prizes_name[]='';
        }

        $my_activity=db('lottery_record')->field('prize,uid')->where("aid={$id}")->select();
        
        $uids = array_column($my_activity, 'uid');

        $member = db('member')->where(['id'=>['in',$uids]])->field('mobile as time')->select();

        $my_activity_time = [];
        foreach ($my_activity as $k => &$v) {
            $name=json_decode($v['prize'],true);
           
            $my_activity_time[$k]['prize_name']=$name['prize_name'];

            if(isset($member[$k]['time'])){
                $my_activity_time[$k]['time']=substr_replace($member[$k]['time'],'*******',4);
            }else{
                $my_activity_time[$k]['time']=substr_replace('13333358802','*******',3);;
            }
        }
        
        $this->assign('activity_name',json_encode($activity_prizes_name));
        $this->assign('id',$id);
        $this->assign('my_activity',$my_activity_time);
        $this->assign('activity',$activity);
        $this->assign('activity_prizes_list',$activity_prizes_list);
        $this->assign('mobile',$user_info['mobile']);
        return $this->fetch();
    }

    //出奖品
    public function prize()
    {
        $user_info = Session::get('user_info');
        
        if(empty($user_info))$this->error('请刷新页面,授权登录!');
        if(empty($user_info['mobile']))$this->error("请绑定手机后，才能抽奖!");

        $activity_id = input('activity_id');

        $where = ['id'=>$activity_id];
        $activity = db('activity')->where($where)->find();

        if(empty($activity))$this->error('参数非法!');

        if($activity['status'] == '-1')$this->error('抽奖活动已关闭!');

        if($activity['start_time'] != 0 && $activity['end_time'] != 0){
            if($activity['start_time'] > time())$this->error('单纯玩游戏，抽奖活动还没开始!');
            if($activity['end_time'] < time())$this->error('抽奖活动已过期!');
        }

        if($activity['lottery_time'] == 0){
            $lottery_record_count = db('lottery_record')->where("aid={$activity_id} and uid={$user_info['id']}")->count();
        }else{
            date_default_timezone_set('PRC');//中华人民共和国时区
            $prize_start = strtotime(date("Y-m-d H:i:s",time()));
            $start_time = $prize_start-86400*$activity['lottery_time'];
            
            
            $lottery_record_count = db('lottery_record')->where("aid={$activity_id} and uid={$user_info['id']} and time >= {$start_time} and time <={$prize_start}")->count();
        }
        
        if($lottery_record_count >= $activity['number_draws'])$this->error('抽奖次数已用完!');
 
        //查询是否允许抽奖 
        $activityer = db('activityer')->where(['aid'=>$activity_id])->select();

        if(!empty($activityer)){
            $mobile = array_column($activityer, 'mobile');
            if(!in_array($user_info['mobile'], $mobile))$this->error('您尚未报名活动，请联系您的客服报名活动!');
        }else{
            $this->error('没有开放抽奖权限!');
        }

        $activity_list = db('activity_prizes')->where("aid={$activity_id} and stock > 0")->select();

        if(empty($activity_list))$this->error('没有奖品可抽!');

        $prize = [];
        foreach ($activity_list as $key => $value) {
            for ($i=0; $i<$value['probability'] ; $i++) { 
                $prize[] = $value['id'];
            }
        }

        $key = $this->getRand($prize);
        //获取奖品id
        $pid = $prize[$key];

        if(!empty($pid)){
            $activity_prizes = db('activity_prizes')->where(['id'=>$pid])->find();

            $activity_prizes_json = json_encode($activity_prizes);

            if($activity_prizes['type'] == '1'){
                $is_winning = $activity_prizes['type'];
            }

            if($activity_prizes['type'] == '2'){
                $is_winning = '-1';
            }

            if($is_winning == '-1')$this->error('抱歉你未中奖!');

            return json([
                "message"=>$activity_prizes['prize_name'],
                "activity_id"=>$activity_id,
                "pid"=>$pid
            ]);
        }else{
            $this->error('网络有误,请稍后在试!');
        }
    }

    //触发红包接口
    public function send_red(){
        $user_info = Session::get('user_info');
        $activity_id = input('activity_id');
        $pid = input('pid');

        if(empty($user_info))$this->error('请刷新页面,授权登录!');
        if(empty($user_info['mobile']))$this->error("请绑定手机后，才能抽奖!");
        if(empty($activity_id))$this->error('活动id为空!');
        if(empty($pid))$this->error('奖品id为空!');


        $where = ['id'=>$activity_id];
        $activity = db('activity')->where($where)->find();

        if(empty($activity))$this->error('参数非法!');

        if($activity['status'] == '-1')$this->error('抽奖活动已关闭!');

        if($activity['start_time'] != 0 && $activity['end_time'] != 0){
            if($activity['start_time'] > time())$this->error('单纯玩游戏，抽奖活动还没开始!');
            if($activity['end_time'] < time())$this->error('抽奖活动已过期!');
        }

        if($activity['lottery_time'] == 0){
            $lottery_record_count = db('lottery_record')->where("aid={$activity_id} and uid={$user_info['id']}")->count();
        }else{
            date_default_timezone_set('PRC');//中华人民共和国时区
            $prize_start = strtotime(date("Y-m-d H:i:s",time()));
            $start_time = $prize_start-86400*$activity['lottery_time'];
            
            
            $lottery_record_count = db('lottery_record')->where("aid={$activity_id} and uid={$user_info['id']} and time >= {$start_time} and time <={$prize_start}")->count();
        }

        if($lottery_record_count >= $activity['number_draws'])$this->error('抽奖次数已用完!');
 
        //查询是否允许抽奖 
        $activityer = db('activityer')->where(['aid'=>$activity_id])->select();
        if(!empty($activityer)){
            $mobile = array_column($activityer, 'mobile');
            if(!in_array($user_info['mobile'], $mobile))$this->error('您尚未报名活动，请联系您的客服报名活动!');
        }else{
            $this->error('没有开放抽奖权限!');
        }

        $activity_list = db('activity_prizes')->where("aid={$activity_id} and stock > 0")->select();

        if(empty($activity_list))$this->error('没有奖品可抽!');

        $activity_prizes = db('activity_prizes')->where(['id'=>$pid])->find();

        if($activity_prizes['stock'] > 0){
            $activity_prizes_json = json_encode($activity_prizes);     
            $activity_prizes_money = $activity_prizes['money']*100;
            $hongbao_bool = true;

            // 启动事务
            Db::startTrans();
            try{
                db('activity_prizes')->where("id=$pid and stock > 0")->setDec('stock');

                $activity_prizes_data = [
                    'uid'=>$user_info['id'],
                    'aid'=>$activity_id,
                    'mobile'=>$user_info['mobile'],
                    'is_winning'=>1,
                    'prize'=>$activity_prizes_json,
                    'time'=>time()
                ];

                db('lottery_record')->insert($activity_prizes_data);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $hongbao_bool = false;
                // 回滚事务
                Db::rollback();
            }

            if($hongbao_bool){
                //活动关闭先注释掉
                $wechat = new wetRedClass();

                $hongbao = $wechat->weixin_red_packet($activity_prizes_money,$user_info['wx_openid']);
                $hongbaos = json_decode($hongbao,1);
                
                if(isset($hongbaos['errcode'])){
                    $this->error('网络有误!');
                }
            }else{
                $this->error('网络有误!');
            }
        }else{
            $this->error('网络有误!');
        }
    }

    //绑定手机号
    public function set_mobile(){
        $user_info = Session::get('user_info');
        if(empty($user_info))$this->error('请刷新首页，重新授权登录!');

        $mobile = input('mobile');

        if(empty($mobile))$this->error('手机参数为空!');

        db('member')->where(['id'=>$user_info['id']])->update(['mobile'=>$mobile]);

        $user_info['mobile'] = $mobile;
        Session::set('user_info',$user_info);

        $this->success('绑定成功!');
    }

    //中奖算法
    public function getRand($proArr){
        $result = ''; 
        
        //概率数组的总概率精度 
        $proSum = array_sum($proArr); 
     
        //概率数组循环 
        foreach ($proArr as $key => $proCur) { 
            $randNum = mt_rand(1, $proSum); 
            if ($randNum <= $proCur) { 
                $result = $key; 
                break; 
            } else {
                $proSum -= $proCur;
            } 
        }

        return $result; 
    }
}
